<template>
  <Dialog ref="dialog" title="下载报告" width="600">
    <div v-loading="isLoading">
      <div class="" style="font-size: 14px">
        <div style="color: #333">请点击下载报告。</div>
        <div style="color: #888">
          (注：如遇浏览器拦截无法下载，请选择允许下载；如点击按钮无法直接下载，请在按钮上右键选择链接另存为。)
        </div>
      </div>

      <div class="right" style="margin-top: 30px">
        <el-button color="#004cf7" @click="onClickDownloadImage(1)"
          >下载图片</el-button
        >
        <el-button color="#004cf7" @click="onClickDownloadImage(2)"
          >下载PDF</el-button
        >
      </div>
    </div>
  </Dialog>
</template>
<script setup>
import Dialog from '@/components/Dialog/Dialog.vue';
import { ref } from 'vue';
import { judgeExport } from '@/api/manage/manage.js';

const judgeInfo = ref({});

const dialog = ref();

const isLoading = ref(false);

// 点击下载图片
function onClickDownloadImage(type) {
  isLoading.value = true;
  downloadData({
    id: judgeInfo.value.id,
    type,
  });
}

async function downloadData(data) {
  try {
    const res = await judgeExport(data);

    const downloadBlob = async (url, fileName) => {
      const blob = await fetch(url).then((res) =>
        res.ok ? res.blob() : Promise.reject(res)
      );
      const urlObject = window.URL.createObjectURL(blob);

      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = urlObject;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      setTimeout(() => {
        window.URL.revokeObjectURL(urlObject);
        document.body.removeChild(a);
      }, 0);

      isLoading.value = false;
    };

    // 根据类型决定文件名和处理方式
    let fileName = '';
    if (data.type == 2) {
      fileName = '测评报告.pdf';
      await downloadBlob(res.data.url, fileName);
    } else if (data.type == 1) {
      fileName = '测评报告.jpg';
      await downloadBlob(res.data.url, fileName);
    }
  } catch (error) {
    console.log('error:', error);
  }
}

function openChange(val) {
  judgeInfo.value = val;
  dialog.value.openChange();
}

defineExpose({
  openChange,
});
</script>
<style lang="scss" scoped></style>
